<template>
  <ContentField>
    <div class="row justify-content-md-center" v-if="!$store.state.user.pulling_info">
      <div class="col-3">
        <form v-on:submit.prevent="login">
          <div class="mb-3">
            <label for="username" class="form-label">用户名</label>
            <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">密码</label>
            <input v-model="password" type="password" class="form-control" id="password" placeholder="请输入密码">
          </div>
          <div class="error-message">{{ error_message }}</div>
          <button type="submit" class="btn btn-primary">提交</button>
        </form>
      </div>
    </div>
  </ContentField>
</template>

<script>
import ContentField from "@/components/ContentField";
import {ref} from 'vue';
import {useStore} from 'vuex'
import router from "@/router";

export default {
  name: "UserAccountLoginView",
  components: {
    ContentField
  },
  setup() {
    const store = useStore();     //新建一个store vuex全局信息
    let username = ref('');
    let password = ref('');
    let error_message = ref('');

    //刷新页面时,验证是否已经登录用户(localStorage 游览器中的数据)
    const jwt_token = localStorage.getItem("Jwt-token");
    if (jwt_token)                 //不为空
    {
      store.commit("updateToken", jwt_token);
      store.dispatch("getInfo", {
        success() {               //回调函数,成功返回首页
          router.push({name: 'home'});
          store.commit("updatePullingInfo", false);
        }, error() {
          store.commit("updatePullingInfo", false);
        }
      })
    } else {
      store.commit("updatePullingInfo", false);
    }

    let login = () => {         //form表单点击=> 触发login函数 => 触发getInfo函数
      error_message.value = "";
      store.dispatch("login", {
        username: username.value,
        password: password.value,
        success() {
          store.dispatch("getInfo", {
            success() {
              router.push({name: 'home'});
              // console.log(store.state.user);
            }
          })
        },
        error() {
          error_message.value = "用户名或者密码错误";
        }
      })
    }

    return {
      username,
      password,
      error_message,
      login
    }
  }
}
</script>

<style scoped>
.error-message {
  color: red;
}

button {
  width: 100%;
}
</style>